package com.yanqu.road.web.controller.usercenter;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.servercenter.*;
import com.yanqu.road.entity.web.HttpGameWebParam;
import com.yanqu.road.server.manger.HotPackVersionMgr;
import com.yanqu.road.server.manger.PackageVersionMgr;
import com.yanqu.road.server.manger.WhiteIpMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.string.StringUtils;
import com.yanqu.road.web.controller.BaseGameHttpServlet;
import com.yanqu.road.web.controller.usercenter.logic.ServerListHelper;
import com.yanqu.road.web.util.IpAddressHelper;
import org.apache.commons.codec.binary.Base64;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * @Author wpj
 * @Date 2021/4/22
 */

@WebServlet(urlPatterns = "/getDescContent")
public class GetDescContent extends BaseGameHttpServlet {
    private static Logger logger = LogManager.getLogger(PlayerRoleQuery.class.getName());

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpGameWebParam httpJsonWebParam = new HttpGameWebParam();
        String param = request.getParameter("param") == null ? "" : request.getParameter("param");
        try {
            param = new String(Base64.decodeBase64(param));
            param = URLDecoder.decode(param, "UTF-8");
            JSONObject paramObj = (JSONObject) JSONObject.parse(param);
            httpJsonWebParam.setLanguage(StringUtils.autoToUtf8(paramObj.getString("language")));
            httpJsonWebParam.setParam(param);
            httpJsonWebParam.setParamObj(paramObj);
        } catch (Exception e) {
            logger.error("json格式出错！ json 字符串param为{}", param, e);
        }

        JSONObject paramObj = httpJsonWebParam.getParamObj();
        String language = httpJsonWebParam.getLanguage();
        String packageVersion;
        String packageMark;
        String hotPackVersion;

        try {
            packageVersion = paramObj.getString("pVersion");
            packageMark = paramObj.getString("packageMark");
            hotPackVersion = paramObj.getString("rVersion");
        } catch (Exception e) {
            logger.error("packageServerList request json格式出错！ json 字符串param为{}", httpJsonWebParam.getParam(), e);
            sendBase64Message(response, getUrlEncodeResultObj(GameErrorCode.E_REQUEST_ARGUMENT_ERROR, language).toJSONString());
            return;
        }
        if (null == hotPackVersion || null == packageVersion || null == packageMark) {
            logger.error("packageServerList request lost argument！param为{}", httpJsonWebParam.getParam());
            sendBase64Message(response, getUrlEncodeResultObj(GameErrorCode.E_REQUEST_ARGUMENT_ERROR, language).toJSONString());
            return;
        }

        PackageMark packageMarkData = PackageVersionMgr.getPackageMark(packageMark);
        if (null == packageMarkData) {
            logger.error("packageServerList packageMark no find, packageMark:{}, packageVersion:{}", packageMark, packageVersion);
            sendBase64Message(response, getUrlEncodeResultObj(GameErrorCode.E_PACKAGE_MARK_NO_FOUND, language).toJSONString());
            return;
        }

        boolean isReview = false;
        boolean isWhiteUser = false;
        int forwardServer = 0;
        boolean isNeedOldDeal = ServerListHelper.isNeedOldDeal(packageMark, isWhiteUser, forwardServer);

        if(isNeedOldDeal) {
            //获取包体信息
            PackageVersion versionData = PackageVersionMgr.getPackageVersion(packageMark, packageVersion);
            if (null == versionData) {
                logger.info("packageServerList packageVersion no find, packageMark:{}, packageVersion:{}", packageMark, packageVersion);
                sendBase64Message(response, getUrlEncodeResultObj(GameErrorCode.E_PACKAGE_VERSION_NO_FOUND, "").toJSONString());
                return;
            }
            //获取热更包体信息
            HotPackVersion hotPackData = HotPackVersionMgr.getHotPackVersion(packageMark, packageVersion, hotPackVersion);
            if (null == hotPackData) {
                logger.info("packageServerList hotPackVersion no find, packageMark:{}, packageVersion:{}, hotPackVersion:{}",
                        packageMark, packageVersion, hotPackVersion);
                sendBase64Message(response, getUrlEncodeResultObj(GameErrorCode.E_HOT_PACK_VERSION_NO_FOUND, language).toJSONString());
                return;
            }
            isReview = hotPackData.isReview();
        }else {
            //获取热更包体信息
            HotfixVersion hotPackData = HotPackVersionMgr.getHotfixVersion(packageMark, packageVersion, hotPackVersion, false, 0);
            if (null != hotPackData) {
                isReview = hotPackData.isReview();
            }
        }

        String ip = IpAddressHelper.getIpAddr(request);
        if (WhiteIpMgr.isBlackIp(ip)) {
            isReview = true;
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("ts", isReview);

        PackageMjbContent packageMjbContent = PackageVersionMgr.getPackageContent(packageMark, isReview);
        String content;
        if (packageMjbContent == null) {
            content = "";
        } else {
            content = packageMjbContent.getContent();
        }
        try {
            content = URLEncoder.encode(content, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        jsonObject.put("content", content);
        jsonObject.put("dds", System.currentTimeMillis());
        sendBase64Message(response, jsonObject.toJSONString());
    }

    private void sendBase64Message(HttpServletResponse response, String msg) throws UnsupportedEncodingException {
        sendMessage(response, Base64.encodeBase64String(msg.getBytes("utf-8")));
    }
}
